package com.example.demo03_mvm.view;

import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.demo03_mvm.viewmodel.BaseViewModel;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseFragment<VM extends BaseViewModel,DB extends ViewDataBinding> extends Fragment {

    protected VM vm;
    protected DB db;
    protected abstract int inflateLayout();
    protected abstract void initData();
    protected abstract void initView();
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        db=DataBindingUtil.inflate(inflater,inflateLayout(),container,false);
        createViewModel();
        initView();
        initData();

        return db.getRoot();
    }

    public void createViewModel(){
        if(vm==null){
            Class mClass;
            Type type = getClass().getGenericSuperclass();
            if(type instanceof ParameterizedType){
                mClass=(Class) ((ParameterizedType)type).getActualTypeArguments()[0];
            }else{
                mClass=BaseViewModel.class;
            }
            vm=(VM) new ViewModelProvider(this).get(mClass);
        }
    }
}
